package com.quectel.core.module.partyeducationtraining.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.partyeducationtraining.TrainingPersonConstants;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.constants.RedisLockConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partyeducationtraining.dao.TrainingCommentDao;
import com.quectel.core.module.partyeducationtraining.dto.TrainingCommentDto;
import com.quectel.core.module.partyeducationtraining.dto.TrainingDto;
import com.quectel.core.module.partyeducationtraining.dto.TrainingPersonDto;
import com.quectel.core.module.partyeducationtraining.entity.TrainingCommentEntity;
import com.quectel.core.module.partyeducationtraining.service.TrainingCommentService;
import com.quectel.core.module.partyeducationtraining.service.TrainingPersonService;
import com.quectel.core.module.partyeducationtraining.service.TrainingService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2022/05/07 16:40
 */
@DubboService
public class TrainingCommentServiceImpl implements TrainingCommentService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TrainingCommentServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> TRAINING_COMMENT_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "TRAINING_COMMENT_CACHE_BY_ID:%d", id);

    @Autowired
    private TrainingCommentDao trainingCommentDao;
    @Autowired
    private PartyPersonService partyPersonService;
    @Autowired
    private TrainingService trainingService;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private TrainingPersonService trainingPersonService;


    @Override
    public void saveAndUpdate(TrainingCommentDto trainingCommentDto) {
        save(trainingCommentDto);

        TrainingPersonDto dbTrainingPersonDto = trainingPersonService.selectOne(trainingCommentDto.getTrainingId(), trainingCommentDto.getPartyPersonId());
        if (Objects.nonNull(dbTrainingPersonDto)) {
            TrainingPersonDto updateObj = new TrainingPersonDto();
            updateObj.setId(dbTrainingPersonDto.getId());
            updateObj.setCommentSubmitted(TrainingPersonConstants.SubmittedEnum.SUBMITTED.getStatus());
            trainingPersonService.updateById(updateObj);
        }
    }

    @Override
    public TrainingCommentDto selectOne(Long personId, Long trainingId) {
        TrainingCommentEntity trainingCommentEntity = trainingCommentDao.selectOne(new LambdaQueryWrapper<TrainingCommentEntity>()
                .eq(TrainingCommentEntity::getPartyPersonId, personId)
                .eq(TrainingCommentEntity::getTrainingId, trainingId)
                .last(SqlConstants.MYSQL_LIMIT_ONE));
        TrainingCommentDto trainingCommentDto = CopyUtils.copyObj(trainingCommentEntity, TrainingCommentDto.class);
        paddingField(trainingCommentDto);
        return trainingCommentDto;
    }

    @Override
    public TrainingCommentDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                TRAINING_COMMENT_CACHE_BY_ID_FUNC.apply(id),

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public TrainingCommentDto selectById(Long id) {
        TrainingCommentEntity entity = trainingCommentDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, TrainingCommentDto.class));
    }

    @Override
    public List<TrainingCommentDto> queryList(Map<String, Object> params) {
        List<TrainingCommentEntity> list = trainingCommentDao.queryList(params);
        List<TrainingCommentDto> result = CopyUtils.copyList(list, TrainingCommentDto.class);
        result.forEach(this::paddingField);
        return result;
    }

//    private void personConditionHand(Map<String, Object> params) {
//        Map<String, Object> queryUserMap = new HashMap<>();
//        queryUserMap.put(LambdaUtil.getFieldName(DeptPersonDto::getName), params.get("personName"));
//        queryUserMap.put(LambdaUtil.getFieldName(DeptPersonDto::getMobile), params.get("personMobile"));
//
//        if (!MapUtils.allValueIsEmpty(queryUserMap)) {
//            List<DeptPersonDto> personDtos = deptPersonService.queryList(queryUserMap);
//            params.put("personIds", personDtos.stream().map(DeptPersonDto::getId).toArray(Long[]::new));
//        }
//    }

    private TrainingCommentDto paddingField(TrainingCommentDto dto) {
        if (dto != null) {
            PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectCacheById(dto.getPartyId());
            dto.setParty(partyOrganizationDto);

            TrainingDto trainingDto = trainingService.selectById(dto.getTrainingId());
            dto.setTraining(trainingDto);

            PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(dto.getPartyPersonId());
            dto.setPartyPerson(partyPersonDto);
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return trainingCommentDao.queryTotal(params);
    }

    @Override
    @Lock(lockExpresses = RedisLockConstants.TRAINING_LOCK + "#{#dto.trainingId}")
    public Long save(TrainingCommentDto dto) {
        TrainingCommentEntity entity = CopyUtils.copyObj(dto, TrainingCommentEntity.class);
        entity.setId(Snowflake.nextId());
        trainingCommentDao.insert(entity);
        changeTrainingCommentCount(dto.getTrainingId(), 1);
        return entity.getId();
    }

    /**
     * 关联更新评价数
     *
     * @param trainingId 课程id
     * @param c          计数
     */
    private void changeTrainingCommentCount(Long trainingId, int c) {
        TrainingDto dbTrainingDto = trainingService.selectById(trainingId);
        TrainingDto newlyDto = new TrainingDto();
        newlyDto.setId(dbTrainingDto.getId());
        newlyDto.setTrainingCommentCount(dbTrainingDto.getTrainingCommentCount() == null
                ? c : dbTrainingDto.getTrainingCommentCount() + c);
        trainingService.updateById(newlyDto);
    }

    @Override
    public void updateById(TrainingCommentDto dto) {
        TrainingCommentEntity entity = CopyUtils.copyObj(dto, TrainingCommentEntity.class);
        trainingCommentDao.updateById(entity);
        CacheKit.invalidRedisCache(TRAINING_COMMENT_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void updateAllColumnById(TrainingCommentDto dto) {
        TrainingCommentEntity entity = CopyUtils.copyObj(dto, TrainingCommentEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, trainingCommentDao);

        CacheKit.invalidRedisCache(TRAINING_COMMENT_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void deleteById(Long id) {
        trainingCommentDao.deleteById(id);

        CacheKit.invalidRedisCache(TRAINING_COMMENT_CACHE_BY_ID_FUNC.apply(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            TrainingCommentDto trainingCommentDto = selectCacheById(id);
            if (trainingCommentDto != null) {
                changeTrainingCommentCount(trainingCommentDto.getTrainingId(), -1);
            }
            deleteById(id);
        }
    }
}
